package cn.ciis.ciis.dictionary;

import cn.ciis.basic.base.BaseCache;
import cn.ciis.basic.base.BaseService;
import cn.ciis.basic.kit.J2CacheKit;
import cn.ciis.basic.model.Dictionary;
import cn.ciis.basic.model.Equipment;
import cn.ciis.basic.plugin.CiisPlugs;
import cn.ciis.ciis.equipment.EquipmentAdminService;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import org.tio.core.Tio;

import java.util.Comparator;
import java.util.List;

/**
 * 数据字典 管理
 * 描述：
 * @author 冉志林
 */
public class DictionaryAdminService extends BaseService {

    private Dictionary dao = new Dictionary().dao();

    @Inject
    EquipmentAdminService equipmentAdminService;

    @Override
    public Model getDao() {
        return dao;
    }

    /**
     * 查询一级栏目
     * @return
     */
    public List<Dictionary> findFirstDictionaryList(){
        return dao.find("SELECT * FROM `ciis_dictionary` where pid=0 and state=0");
    }

    //根据pid查询最大的编号number
    public Record findMaxNuber(int pid){
        return Db.findFirst("SELECT MAX(number) maxNumber FROM `ciis_dictionary` where pid=?",pid);
    }

    /**
     * 根据pid查询子列表
     * @param pid
     * @return
     */
    public List<Dictionary> findByPid(int pid){

        return dao.template(StrUtil.format("{}.findByPid",getTable()), Kv.by("pid",pid)).find();
    }

    /**
     * 启用和禁用传感器类型
     * @param state 0启用1禁用
     * @param id
     * @return
     */
    public boolean modifyState(int id,int state){
        Db.tx(()->{
            //目标元素下标
            int[] index =new int[]{0};

            if(state == 0){//启用
                Dictionary dictionary = Dictionary.dao.findById(id);
                List<Dictionary> dictionaryList= (List<Dictionary>) J2CacheKit.get(BaseCache.EQUIPMENT_DATA_DICTIONARY,"01", s -> {
                    return  findByPid(1);
                }).getValue();

                dictionaryList.add(dictionary);//将新启用的类型加入list
                dictionaryList.sort(Comparator.comparing(Dictionary::getNumber));//按照number从小到大排序

                for (int i = 0; i < dictionaryList.size(); i++) {
                    if(dictionaryList.get(i).getId() == id){
                        index[0] =i;
                        dictionaryList.get(i).setState(state);
                        dictionaryList.get(i).update();//修改标记
                        break;
                    }
                }

                //查询所有没有禁用的分站
                List<Equipment> equipmentList = equipmentAdminService.findByValidityLen(-1);

                equipmentList.forEach(equipment -> {

                    if(StrKit.notBlank(equipment.getValidity())){
                        int temp =equipment.getValidity().length() - index[0];
                        if(temp <0){
                            StrBuilder builder = StrBuilder.create(equipment.getValidity());
                            while (temp <=0){
                                builder.append('0');
                                temp++;
                            }
                            equipment.setValidity(builder.toString());
                        }else{
                            char[] chars = equipment.getValidity().toCharArray();

                            StrBuilder builder = StrBuilder.create();
                            for (int i = 0; i < chars.length; i++) {
                                if(i == index[0]){
                                    builder.append('0');
                                }
                                builder.append(chars[i]);
                            }
                            equipment.setValidity(builder.toString());
                        }
                    }else {
                        StrBuilder builder = StrBuilder.create();
                        while (index[0] >=0){
                            builder.append('0');
                            index[0]--;
                        }
                        equipment.setValidity(builder.toString());
                    }
                    equipment.update();
                    if(equipment.isConnect()){
                        J2CacheKit.set(BaseCache.EQUIPMENT_TIMED_CACHE, equipment.getCode(), equipment);//更新缓存数据
                        Tio.close(CiisPlugs.ciisServerTioConfig,equipment.getIp(),equipment.getPort(),null,"服务端更新配置");
                    }
                });


            }else if(state ==1){//禁用
                //传感器类型缓存
                List<Dictionary> dictionary= (List<Dictionary>) J2CacheKit.get(BaseCache.EQUIPMENT_DATA_DICTIONARY,"01", s -> {
                    return  findByPid(1);
                }).getValue();

                for (int i = 0; i < dictionary.size(); i++) {
                    if(dictionary.get(i).getId() == id){
                        index[0] =i;
                        dictionary.get(i).setState(state);
                        dictionary.get(i).update();//修改标记
                        break;
                    }
                }

                List<Equipment> equipmentList = equipmentAdminService.findByValidityLen(index[0]);

                equipmentList.forEach(equipment -> {


                    char[] chars = equipment.getValidity().toCharArray();

                    StrBuilder builder = StrBuilder.create();

                    for (int i = 0; i < chars.length; i++) {
                        if(i != index[0]){
                            builder.append(chars[i]);
                        }
                    }
                    equipment.setValidity(builder.toString());
                    equipment.update();
                    if(equipment.isConnect()){
                        J2CacheKit.set(BaseCache.EQUIPMENT_TIMED_CACHE, equipment.getCode(), equipment);//更新缓存数据
                        Tio.close(CiisPlugs.ciisServerTioConfig,equipment.getIp(),equipment.getPort(),null,"服务端更新配置");
                    }
                });
            }

            //刷新缓存
            J2CacheKit.set(BaseCache.EQUIPMENT_DATA_DICTIONARY,"01", findByPid(1));
            return true;
        });
        return true;
    }
}